package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nineclock.common.entity.PageResult;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.dto.SysRoleDTO;
import com.nineclock.system.excel.ExcelMember;
import com.nineclock.system.excel.MemberParseListener;
import com.nineclock.system.mapper.*;
import com.nineclock.system.pojo.*;
import com.nineclock.system.service.SysCompanyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysCompanyUserServiceImpl implements SysCompanyUserService {

    @Autowired
    SysCompanyUserMapper sysCompanyUserMapper;
    @Autowired
    SysDepartmentMapper sysDepartmentMapper;

    @Override
    public SysCompanyUserDTO getCurrentAdmin() {

        //获取企业信息
        Long companyId = CurrentUserHolder.get().getCompanyId();
        //查询到当前企业的管理员信息
        SysCompanyUser sysCompanyUser = sysCompanyUserMapper.queryMainAdminCompanyUser(companyId);

        if (sysCompanyUser == null){
            throw new NcException(ResponseEnum.COMPANY_ADMIN_NOT_EXISTS);
        }

        //如果是，将pojo对象转换为dto对象
        return BeanHelper.copyProperties(sysCompanyUser,SysCompanyUserDTO.class);
    }

    @Override
    public List<SysCompanyUserDTO> queryCompanyMemberList() {
        Long companyId = CurrentUserHolder.get().getCompanyId();
        LambdaQueryWrapper<SysCompanyUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysCompanyUser::getCompanyId,companyId);
        lambdaQueryWrapper.eq(SysCompanyUser::getEnable,1);

        List<SysCompanyUser> sysCompanyUsers = sysCompanyUserMapper.selectList(lambdaQueryWrapper);
        if (sysCompanyUsers == null){
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }

        List<SysCompanyUserDTO> sysCompanyUserDTOS = BeanHelper.copyWithCollection(sysCompanyUsers, SysCompanyUserDTO.class);

        return sysCompanyUserDTOS;
    }

    @Override
    public PageResult<SysCompanyUserDTO> members(Integer page, Integer pageSize, String keyword, Long departmentId) {
        //存储部门及子部门的集合
        List<Long> ids = new ArrayList<>();
        ids.add(departmentId);
        this.childDepartmentId(ids,departmentId);

        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(SysCompanyUser::getCompanyId,CurrentUserHolder.get().getCompanyId());
        wrapper.in(SysCompanyUser::getDepartmentId,ids);
        if (keyword!=null){
            wrapper.and(wrapper1 ->{
                wrapper1.like(SysCompanyUser::getUserName,keyword)
                          .or().like(SysCompanyUser::getMobile,keyword)
                          .or().like(SysCompanyUser::getWorkNumber,keyword);
              });



        }

        Page<SysCompanyUser> companyUserPage = new Page<>(page,pageSize);

        companyUserPage = sysCompanyUserMapper.selectPage(companyUserPage, wrapper);
        //查询出要展示的数据
        List<SysCompanyUser> records = companyUserPage.getRecords();
        if(records!=null){
            List<SysCompanyUserDTO> sysCompanyUserDTOS = BeanHelper.copyWithCollection(records, SysCompanyUserDTO.class);
            PageResult<SysCompanyUserDTO> pageResult = new PageResult<>(companyUserPage.getTotal(),companyUserPage.getPages(),sysCompanyUserDTOS);
            return pageResult;
        }



        return new PageResult<>();
    }

    @Override
    public void uploadExcel(MultipartFile excelFile) throws IOException {
        if (excelFile == null){
            throw new NcException(ResponseEnum.FILE_NOT_FOUND);
        }
        //解析excel
        EasyExcel.read(excelFile.getInputStream(), ExcelMember.class,new MemberParseListener(this)).sheet(0).doRead();
    }

    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;
    @Autowired
    SysCompanyUserRoleMapper companyUserRoleMapper;
    @Override
    public void saveData(List<ExcelMember> memberList) {
        for (ExcelMember excelMember : memberList) {
            //1.1 判定系统用户手机号 , 邮箱是否已经被注册(用户表)
           LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
           wrapper.eq(SysUser::getMobile,excelMember.getMobile())
                   .or().eq(SysUser::getEmail,excelMember.getEmail());
            Integer count = sysUserMapper.selectCount(wrapper);
            if (count>0){
                throw new NcException(ResponseEnum.USER_MOBILE_EMAIL_EXISTS);
            }
            //1.2 判定企业用户工号是否被占用（员工表）
            LambdaQueryWrapper<SysCompanyUser> numWrapper = new LambdaQueryWrapper<>();
            numWrapper.eq(SysCompanyUser::getWorkNumber,excelMember.getWorkNumber());
            Integer numCount = sysCompanyUserMapper.selectCount(numWrapper);
            if (numCount>0){
                throw new NcException(ResponseEnum.SERVER_ERROR);
            }
            //封装系统用户数据 , 对密码进行加密
            SysUser user = new SysUser();
            user.setUsername(excelMember.getName());
            user.setMobile(excelMember.getMobile());
            user.setEmail(excelMember.getEmail());
            user.setStatus((short)1);
            user.setCreateTime(new Date());
            user.setPassword(new BCryptPasswordEncoder().encode("123456")); //初始密码
            user.setLastLoginCompanyId(CurrentUserHolder.get().getCompanyId());

            sysUserMapper.insert(user);
            //员工
            SysCompanyUser companyUser = new SysCompanyUser();
            companyUser.setUserName(excelMember.getName());
            companyUser.setUserId(user.getId());
            companyUser.setCompanyId(CurrentUserHolder.get().getCompanyId());
            companyUser.setCompanyName(CurrentUserHolder.get().getCompanyName());
            companyUser.setEnable((short)1);
            companyUser.setCreateTime(new Date());
            companyUser.setMobile(excelMember.getMobile());
            companyUser.setEmail(excelMember.getEmail());
            companyUser.setWorkNumber(excelMember.getWorkNumber());
            companyUser.setOfficeAddress(excelMember.getWorkAddr());
            companyUser.setTimeEntry(excelMember.getEntryTime());
            companyUser.setPost(excelMember.getPosition());
            companyUser.setRemark(excelMember.getDesc());

            //设置部门信息
            //根据部门名称查询部门对象
            LambdaQueryWrapper<SysDepartment> departmentQw = new LambdaQueryWrapper<>();
            departmentQw.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
            departmentQw.eq(SysDepartment::getName, excelMember.getDepartmentName());
            SysDepartment department = sysDepartmentMapper.selectOne(departmentQw);
            if(department != null){
                companyUser.setDepartmentId(department.getId());
                companyUser.setDepartmentName(department.getName());
            }
            sysCompanyUserMapper.insert(companyUser);

            //根据角色名称 查询角色对象
            LambdaQueryWrapper<SysRole> roleQw = new LambdaQueryWrapper<>();
            roleQw.eq(SysRole::getCompanyId, CurrentUserHolder.get().getCompanyId());
            roleQw.eq(SysRole::getRoleDesc, excelMember.getRoleName());
            SysRole role = sysRoleMapper.selectOne(roleQw);

            if(role != null){
                //员工和角色的关系
                SysCompanyUserRole companyUserRole = new SysCompanyUserRole();
                companyUserRole.setRoleId(role.getId());
                companyUserRole.setCompanyUserId(companyUser.getId());
                companyUserRole.setCompanyId(CurrentUserHolder.get().getCompanyId());

                companyUserRoleMapper.insert(companyUserRole);
            }



        }
    }

    /**
     * 根据部门id计算员工人数
     * @param departmentIds
     * @return
     */
    @Override
    public Integer queryUserCountByDepartmentIds(List<Long> departmentIds) {
        List<Long> ids = new ArrayList<>();
        ids.addAll(departmentIds);
        for (Long departmentId : departmentIds) {
            //查询子部门id并添加到 集合中
            this.childDepartmentId(ids, departmentId);
        }

        //查询员工数量
        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.in(SysCompanyUser::getDepartmentId, ids);

        Integer count = sysCompanyUserMapper.selectCount(wrapper);

        return count == null ? 0 : count;
    }

    @Override
    public SysCompanyUserDTO queryOne(String mobile) {
        if(mobile == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.eq(SysCompanyUser::getMobile, mobile);
        SysCompanyUser companyUser = sysCompanyUserMapper.selectOne(wrapper);
        if(companyUser != null){
            return  BeanHelper.copyProperties(companyUser, SysCompanyUserDTO.class);
        }
        return null;
    }

    @Override
    public List<SysCompanyUserDTO> queryCompanyUser(Long companyId, Long userId) {
        //健壮性判断
        if(userId == null){
            return null;
        }

        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        if(companyId != null){
            wrapper.eq(SysCompanyUser::getCompanyId, companyId);
        }
        wrapper.eq(SysCompanyUser::getUserId, userId);
        wrapper.eq(SysCompanyUser::getEnable, 1);

        List<SysCompanyUser> companyUserList = sysCompanyUserMapper.selectList(wrapper);
        if(CollectionUtil.isNotEmpty(companyUserList)){
            List<SysCompanyUserDTO> companyUserDTOList = BeanHelper.copyWithCollection(companyUserList, SysCompanyUserDTO.class);
            //循环员工列表， 查询每个员工的角色信息
            for (SysCompanyUserDTO companyUserDTO : companyUserDTOList) {
                List<SysRole> roleList = sysRoleMapper.selectRoleListByCompanyId(companyUserDTO.getId(), companyUserDTO.getCompanyId());
                if(CollectionUtil.isNotEmpty(roleList)){
                    companyUserDTO.setRoles(BeanHelper.copyWithCollection(roleList, SysRoleDTO.class));
                }
            }

            return companyUserDTOList;
        }
        return null;
    }

    //
    public void childDepartmentId(List<Long> ids,Long parentId){
        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getCompanyId,CurrentUserHolder.get().getCompanyId());
        wrapper.eq(SysDepartment::getParentId,parentId);
        List<SysDepartment> sysDepartments = sysDepartmentMapper.selectList(wrapper);
        if (sysDepartments!=null){
            //取出部门列表的id
            List<Long> departmentIds = sysDepartments.stream()
                    .map(sysDepartment -> {//map表示映射
                        return sysDepartment.getId();
                    }).collect(Collectors.toList());//collection表示映射的类型

            ids.addAll(departmentIds);
            for (Long depId : departmentIds) {
                this.childDepartmentId(ids,depId);
            }

        }
    }
}
